<?php
/**
 * A button that allows a user to view readonly details of a record. This is
 * disabled by default and intended for use in readonly {@link GridField}
 * instances.
 *
 * @package framework
 * @subpackage fields-gridfield
 */
class GridFieldEmailButton implements GridField_ColumnProvider {
    protected $email_subject;
    protected $email_template;
    protected $email_field = 'Email';
    protected $email_from;
    
    public static function inst($subject, $template){
        return new GridFieldEmailButton($subject, $template);
    }
    
    /**
     * Creates a new GridFieldEmailButton field
     *
     * @param string $subject
     * @param string $template
     */
    public function __construct($subject, $template) {
        $this->setEmailSubject($subject)->setEmailTemplate($template);
    }

	public function augmentColumns($field, &$cols) {
		if(!in_array('Actions', $cols)) $cols[] = 'Actions';
	}

	public function getColumnsHandled($field) {
		return array('Actions');
	}

	public function getColumnContent($field, $record, $col) {
		if(Email::is_valid_address($record->getField($this->getEmailField()))) {
		    Requirements::javascript('general/javascript/GridFieldEmailButton.js');
		    Requirements::css('general/css/GridFieldEmailButton.css');
			$data = new ArrayData(array(
				'Link' => Controller::join_links($field->Link('item'), $record->ID, 'email', sprintf('?field=%s&template=%s&subject=%s&from=%s', $this->getEmailField(), $this->getEmailTemplate(), $this->getEmailSubject(), $this->getEmailFrom())),
				'Subject' => $this->getEmailSubject()
			));
			return $data->renderWith('GridFieldEmailButton');
		}
	}

	public function getColumnAttributes($field, $record, $col) {
		return array('class' => 'col-buttons');
	}

	public function getColumnMetadata($gridField, $col) {
		return array('title' => null);
	}
    
    public function setEmailField($fieldName){
        $this->email_field = $fieldName;
        return $this;
    }
    
    public function getEmailField(){
        return $this->email_field;
    }
    
    public function setEmailTemplate($template){
        $this->email_template = $template;
        return $this;
    }
    
    public function getEmailTemplate(){
        return $this->email_template;
    }
    
    public function setEmailSubject($subject){
        $this->email_subject = $subject;
        return $this;
    }
    
    public function getEmailSubject(){
        return $this->email_subject;
    }
    
    public function setEmailFrom($from){
        $this->email_from = $from;
        return $this;
    }
    
    public function getEmailFrom(){
        return $this->email_from;
    }
}
